<?php
// +----------------------------------------------------------------------
// | 志进科技
// +----------------------------------------------------------------------
// | 官方网站: http://www.zhijin101.com
// +----------------------------------------------------------------------
// | Author: 张亚伟 <1743325520@qq.com>
// +----------------------------------------------------------------------

namespace Api\Controller;
/**
 * 会员中心
 */
class MemberController extends ApiController
{
    protected $noCheck = ['offline_rank'];

    function _initialize() {
        parent::_initialize();
    }

    /**
     * 下线人数
     * @return json
     */
    public function referrals_num()
    {
        // 已购买
        $buy_num = M('user')->where(['first_leader'=>$this->uid, 'total_amount'=>['gt', 0]])->count();
        // 未购买
        $no_buy_num = M('user')->where(['first_leader'=>$this->uid, 'total_amount'=>0])->count();
        $info = [
            'buy_num'       => $buy_num,
            'no_buy_num'    => $no_buy_num,
            'total_num'     => $buy_num+$no_buy_num,
        ];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
    }

    /**
     * 我的下线
     * @return   [type]     [description]
     */
    public function my_referrals()
    {
        $is_buy = I('is_buy');
        $referral_type = I('referral_type', 0);
        $page = I('page', 1);
        $size = I('size', 20);
        $map = [];
        switch ($referral_type) {
            case '1':// 一级下线
                $map['first_leader'] = $this->uid;
                break;
            case '2':// 二级下线
                $map['second_leader'] = $this->uid;
                break;
            default:// 第一和第二下级
                $map['first_leader|second_leader'] = $this->uid;
                break;
        }
        switch ($is_buy) {
            case '1'://未消费
                $map['total_amount'] = 0;
                break;
            case '2'://已消费
                $map['total_amount'] = ['gt', 0];
                break;
        }
        $user_list = M('user')->alias('u')->join('__MEMBER_NO__ mn ON u.id=mn.user_id', 'left')->where($map)->page($page, $size)->field('u.id,u.nickname,u.img,u.phone,u.total_amount,u.is_nearby,u.ctime,mn.member_no')->select();
        if($user_list){
            foreach ($user_list as $key => &$user) {
                $user['ctime'] = date('Y-m-d H:i:s', $user['ctime']);
            }
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$user_list]);
    }

    /**
     * 排行榜
     */
    public function offline_rank()
    {
        $page = I('page');
        $size = I('size');
        $list = M('user')->where(['offline_num'=>['gt', 0]])->order('offline_num desc,offline_time asc')->page($page, $size)->field('id,nickname,img,offline_num')->select();
        if($list){
            if($user_ids = array_column($list, 'id')){
                $member_no = M('member_no')->where(['user_id'=>['in', $user_ids]])->getField('user_id,member_no');
            }else{
                $member_no = [];
            }
            $award_level = M('award_level')->order('max_num asc')->select();
            foreach ($list as $key => &$row) {
                $level_info = [];
                foreach ($award_level as $key => $level_item) {
                    if($row['offline_num'] >= $level_item['min_num']){
                        $level_info = $level_item;
                    }
                }
                if($level_info){
                    $row['level_name'] = $level_info['name'];
                    $row['level_img'] = $level_info['icon'];
                }else{
                    $row['level_name'] = '';
                    $row['level_img'] = '';
                }
                $row['member_no'] = isset($member_no[$row['id']]) ? $member_no[$row['id']] : '';
            }
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
    }

    /**
     * 我的推广排行
     */
    public function my_offline_rank()
    {
        $user = $this->user;
        $member_no = M('member_no')->where(['user_id'=>$this->uid])->find();
        $user_info = [
            'member_no'     => $member_no['member_no'],
            'id'            => $user['id'],
            'nickname'      => $user['nickname'],
            'img'           => $user['img'],
            'offline_num'   => $user['offline_num'],
            'level'         => [],
        ];
        if($user['offline_num']){
            $award_level = M('award_level')->order('max_num asc')->select();
            $level_info = [];
            foreach ($award_level as $key => $level_item) {
                if($user['offline_num'] >= $level_item['min_num']){
                    $level_info = $level_item;
                }
            }
            if($level_info){
                $user_info['level']['id'] = $level_info['id'];
                $user_info['level']['name'] = $level_info['name'];
                $user_info['level']['img'] = $level_info['icon'];
                $user_info['level']['money'] = $level_info['award_money'];
                $is_tx = M('user_level_withdrawal')->where(['user_id'=>$this->uid, 'level'=>$level_info['id']])->find();
                $user_info['level']['is_tx'] = $is_tx ? 1 : 0;
            }
            $sql .= "SELECT count(u.id) as num FROM __USER__ as u WHERE u.offline_num > {$user['offline_num']} OR (u.offline_num = {$user['offline_num']} AND u.offline_time <{$user['offline_time']})";
            $rank_info = M()->query($sql);
            if(empty($rank_info)){
                $rank = 0;
            }else{
                $rank = $rank_info[0]['num'];
            }
        }else{
            $rank = 0;
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'rank'=>$rank, 'user'=>$user_info]);  
    }

    public function agent_order()
    {
        if(!$this->user['is_agent']){
            $this->ajaxReturn(['s'=>true, 'm'=>'你不是区县代理商']);
        }
        $page = I('page');
        $size = I('size');

        $province = '';
        $city = '';
        $district = '';
        if($this->user['agent_city']){
            $agent_city = explode(' ', $this->user['agent_city']);
            $province = !empty($agent_city[0]) ? $agent_city[0] : '';
            $city = !empty($agent_city[1]) ? $agent_city[1] : '';
            $district = !empty($agent_city[2]) ? $agent_city[2] : '';
        }
        $map = [];
        $season = ceil((date('n'))/3);//当月是第几季度
        if($province && $city && $district){
            $season_s_time = mktime(0, 0, 0, $season*3-3+1, 1, date('Y'));
            $season_e_time = mktime(23,59,59, $season*3, date('t', mktime(0, 0 , 0, $season*3,1, date("Y"))),date('Y'));

            $map['ctime'] = [['between', [$season_s_time, $season_e_time]], ['gt', strtotime('2019-01-18')]];
            $map['c_addr'] = ['like', $province.$city.$district.'%'];
        }
        $list = [];
        $total_amount = 0;

        if($map){
            $map['pay_status'] = 1;
            $order_list = M('order')->where($map)->page($page, $size)->select();
            $total_amount = M('order')->where($map)->sum('cprice');
            $total_amount = $total_amount ? $total_amount : 0;
        }
        if(!empty($order_list)){
            if($user_ids = array_column($order_list, 'uid')){
                $member_nos = M('member_no')->where(['user_id'=>['in', $user_ids]])->getField('user_id,member_no');
            }else{
                $member_nos = [];
            }
            foreach ($order_list as $key => $order) {
                $member_no = isset($member_nos[$order['uid']]) ? $member_nos[$order['uid']] : '';
                $list[] = [
                    'member_no' => '会员号'.$member_no,
                    'date'      => date('Y/m/d', $order['ctime']),
                    'money'     => $order['cprice'],
                ];
            }
        }
        $city_arr = [
            'province'  => $province,
            'city'      => $city,
            'district'  => $district,
        ];
        $season_arr = ['1'=>'第一季度', '2'=>'第二季度', '3'=>'第三季度', '4'=>'第四季度'];
        $season = isset($season_arr[$season]) ? $season_arr[$season] : '';
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list, 'city'=>$city_arr, 'season'=>$season, 'total_amount'=>$total_amount]);
    }

    public function agent_past_order()
    {
        if(!$this->user['is_agent']){
            $this->ajaxReturn(['s'=>true, 'm'=>'你不是区县代理商']);
        }
        $page = I('page');
        $size = I('size');

        $province = '';
        $city = '';
        $district = '';
        if($this->user['agent_city']){
            $agent_city = explode(' ', $this->user['agent_city']);
            $province = !empty($agent_city[0]) ? $agent_city[0] : '';
            $city = !empty($agent_city[1]) ? $agent_city[1] : '';
            $district = !empty($agent_city[2]) ? $agent_city[2] : '';
        }
        $map = [
            'c_addr'=>['like', $province.$city.$district.'%'],
            'pay_status'=>1,
            'ctime' =>['gt', strtotime('2019-01-18')],
        ];
        $first_time = M('order')->where($map)->order('ctime asc')->getField('ctime');
        $last_time = M('order')->where($map)->order('ctime desc')->getField('ctime');

        $season = ceil((date('n', $first_time))/3);//第一个是第几季度
        $season_s_time = mktime(0, 0, 0, $season*3-3+1, 1, date('Y', $first_time));
        $season_e_time = mktime(23,59,59, $season*3, date('t', mktime(0, 0 , 0, $season*3,1, date("Y", $first_time))),date('Y', $first_time));

        $season_arr = ['1'=>'第一季度', '2'=>'第二季度', '3'=>'第三季度', '4'=>'第四季度'];

        $list = [];
        if($first_time){
            if($first_time == $last_time){
                $map['ctime'] = [['between', [$season_s_time, $season_e_time]], ['gt', strtotime('2019-01-18')]];
                $season_str = isset($season_arr[$season]) ? $season_arr[$season] : '';
                $total_amount = M('order')->where($map)->sum('cprice');
                $list[] = [
                    'year'          => date('Y', $season_e_time),
                    'season'        => $season_str,
                    'total_amount'  => $total_amount,
                ];
            }else{
                while ($season_e_time < $last_time || ($season_e_time >= $last_time && $season_s_time < $last_time)) {
                    $map['ctime'] = [['between', [$season_s_time, $season_e_time]], ['gt', strtotime('2019-01-18')]];
                    $season_str = isset($season_arr[$season]) ? $season_arr[$season] : '';
                    $total_amount = M('order')->where($map)->sum('cprice');
                    $list[] = [
                        'year'          => date('Y', $season_s_time),
                        'season'        => $season_str,
                        'total_amount'  => $total_amount,
                    ];

                    $season = ceil((date('n', $season_e_time+1))/3);//第一个是第几季度
                    $season_s_time = mktime(0, 0, 0, $season*3-3+1, 1, date('Y', $season_e_time+1));
                    $season_e_time = mktime(23,59,59, $season*3, date('t', mktime(0, 0 , 0, $season*3,1, date("Y", $season_e_time+1))),date('Y', $season_e_time+1));
                }
            }
        }
        $list = array_reverse($list);
        $city_arr = [
            'province'  => $province,
            'city'      => $city,
            'district'  => $district,
        ];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list, 'city'=>$city_arr]);
    }

    /**
     * 佣金列表
     */
    public function commission_list()
    {
        $date = I('date');
        if(empty($date)){
            $date = time();
        }else{
            $date = strtotime($date);
            if($date === false){
                $this->ajaxReturn(['s'=>false, 'm'=>'时间格式错误']);
            }
        }
        $t = date('t', $date);

        $start = mktime(0, 0, 0, date('m', $date) , 1, date('Y', $date)); //上个月的开始日期
        $end = mktime(23, 59, 59, date('m', $date) , $t, date('Y', $date)); //上个月的结束日期
        $map = [
            'user_id'       => $this->uid,
            'create_time'   => [['between', [$start, $end]]],
        ];
        $from_type_arr = ['order'=>'收款', 'return'=>'退款'];
        $list = M('commission_log')->where($map)->order('id desc')->field('id,from_type as type,desc,money,create_time as time')->select();
        if($list){
            foreach ($list as $key => &$row) {
                $row['time'] = date('Y-m-d H:i:s', $row['time']);
                $row['type'] = isset($from_type_arr[$row['type']]) ? $from_type_arr[$row['type']] : '';
            }
        }
        // 收入
        $income = M('commission_log')->where(array_merge($map, ['from_type'=>'order']))->sum('money');
        $income = $income ? $income : 0;
        $income = abs($income);
        // 支出
        $expend = M('commission_log')->where(array_merge($map, ['from_type'=>'return']))->sum('money');
        $expend = $expend ? $expend : 0;
        $expend = abs($expend);
        $first_info  = M('commission_log')->where(['user_id'=>$this->uid])->order('id asc')->find();
        $first_time = null;
        if($first_info){
            $first_time = $first_info['create_time'];
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list, 'date'=>date('Y-m', $date), 'income'=>$income, 'expend'=>$expend, 'first_time'=>$first_time]);
    }

    /**
     * 用户优惠券列表
     */
    public function coupons()
    {
        $coupons = M('UserCoupons')->alias('uc')
        ->join('__SHOP__ s ON s.id=uc.shop_id', 'LEFT')
        ->join('__SHOP_COUPONS__ c ON c.id=uc.coupon_id', 'LEFT')
        ->join('__SHOP_COUPON_TPLS__ ct ON ct.id=uc.tpl_id', 'LEFT')
        ->where(['uc.user_id'=>$this->uid])
        ->order('uc.id desc')
        ->field('uc.id,uc.title,s.shopname,ct.img,uc.is_use,uc.is_condition,uc.condition_amount,uc.discount_amount,uc.use_start_time,uc.use_end_time,uc.create_time')
        ->select();
        if($coupons){
            $now_time = time();
            foreach ($coupons as $key => &$coupon) {
                if($coupon['is_use']){
                    $status = 3;// 已使用
                    $status_desc = "已使用";
                }else{
                    if($now_time < $coupon['use_start_time']){
                        $status = 1;// 未到可使用时间
                        $status_desc = "暂不可用";
                    }else if($now_time > $coupon['use_end_time']){
                        $status = 4;// 过期
                        $status_desc = "已过期";
                    }else{
                        $status = 2;// 可用
                        $status_desc = "立即使用";
                    }
                }
                $coupon['status'] = $status;
                $coupon['status_desc'] = $status_desc;
                $coupon['use_start_time'] = date('Y-m-d', $coupon['use_start_time']);
                $coupon['use_end_time'] = date('Y-m-d', $coupon['use_end_time']);
                $coupon['create_time'] = date('Y-m-d H:i:s', $coupon['create_time']);
                $coupon['condition_amount'] = $coupon['condition_amount']*1;
                $coupon['discount_amount'] = $coupon['discount_amount']*1;
            }
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'coupons'=>$coupons]);
    }

    /**
     * 使用优惠券
     */
    public function use_coupon()
    {
        $user_coupon_id = I('user_coupon_id');
        $userCoupon = M('UserCoupons')->where(['id'=>$user_coupon_id])->find();
        if(empty($userCoupon)){
            $this->ajaxReturn(['s' => false, 'm' => '优惠券不存在']);
        }
        if($userCoupon['user_id']!=$this->uid){
            $this->ajaxReturn(['s' => false, 'm' => '错误调用']);
        }
        if($userCoupon['is_use']){
            $this->ajaxReturn(['s' => false, 'm' => '已使用']);
        }
        $now_time = time();
        if($now_time < $userCoupon['use_start_time']){
            $this->ajaxReturn(['s' => false, 'm' => '未到可使用时间，暂不可用']);
        }
        if($now_time > $userCoupon['use_end_time']){
            $this->ajaxReturn(['s' => false, 'm' => '已过期']);
        }
        $res = M('UserCoupons')->where(['id'=>$user_coupon_id])->save(['is_use'=>1, 'use_time'=>time()]);
        if($res!==false){
            $this->ajaxReturn(['s' => true, 'm' => 'ok']);
        }else{
            $this->ajaxReturn(['s' => false, 'm' => '请求失败']);
        }
    }

    public function coupon_del()
    {
        $user_coupon_id = I('user_coupon_id');
        $userCoupon = M('UserCoupons')->where(['id'=>$user_coupon_id])->find();
        if(empty($userCoupon)){
            $this->ajaxReturn(['s' => false, 'm' => '优惠券不存在']);
        }
        if($userCoupon['user_id']!=$this->uid){
            $this->ajaxReturn(['s' => false, 'm' => '错误调用']);
        }
        $res = M('UserCoupons')->where(['id'=>$user_coupon_id])->delete();
        if($res!==false){
            $this->ajaxReturn(['s' => true, 'm' => 'ok']);
        }else{
            $this->ajaxReturn(['s' => false, 'm' => '删除失败']);
        }
    }
}
